import React, { useEffect } from 'react';
import { Modal, Form, Input, message } from 'antd';
import type { Role, RoleCreateParams, RoleUpdateParams } from '@/api/system';

const { Item: FormItem } = Form;

interface RoleFormProps {
  visible: boolean;
  role?: Role | null;
  onSubmit: (values: RoleCreateParams | RoleUpdateParams) => void;
  onCancel: () => void;
}

const RoleForm: React.FC<RoleFormProps> = ({ visible, role, onSubmit, onCancel }) => {
  const [form] = Form.useForm();

  useEffect(() => {
    if (visible && role) {
      form.setFieldsValue({
        code: role.code,
        name: role.name,
      });
    } else if (visible) {
      form.resetFields();
    }
  }, [visible, role, form]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      onSubmit(role ? { ...values, id: role.id } : values);
    } catch (error) {
      // 静默处理表单验证失败
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <Modal
      title={role ? '编辑角色' : '新增角色'}
      open={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      width={600}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        requiredMark={false}
      >
        <FormItem
          name="code"
          label="角色编码"
          rules={[
            { required: true, message: '请输入角色编码' },
            { min: 2, max: 50, message: '角色编码长度在2-50个字符之间' },
            { pattern: /^[a-zA-Z0-9_]+$/, message: '角色编码只能包含字母、数字和下划线' }
          ]}
        >
          <Input placeholder="请输入角色编码" />
        </FormItem>

        <FormItem
          name="name"
          label="角色名称"
          rules={[
            { required: true, message: '请输入角色名称' },
            { min: 2, max: 50, message: '角色名称长度在2-50个字符之间' }
          ]}
        >
          <Input placeholder="请输入角色名称" />
        </FormItem>
      </Form>
    </Modal>
  );
};

export default RoleForm;